// stucture/calc-mvc/CalcController.java - Controller
//    Handles user interaction with listeners.
//    Calls View and Model as needed.
// Fred Swartz -- December 2004

package Lab_v3;

import java.awt.event.*;
 // Import log4j classes.
 import org.apache.log4j.Logger;
 import org.apache.log4j.PropertyConfigurator;
//import org.sqlite.JDBC;
import java.sql.*;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Enumeration;
import java.lang.*;
import java.io.*;

public class MCQbusiness {

    private dbtables_test_metadata dbobject_test_metadata;
    private dbtables_question_metadata dbobject_question_metadata;
    private dbtables_mcq_options dbobject_mcq_options;
	private ArrayList liveUserAnswers;
    /**
    * @param args the command line arguments
    */
      public static void main(String[] args)  throws ClassNotFoundException {
Class.forName("org.sqlite.JDBC");

dbtables_handler myDb = new dbtables_handler("sqlite","mcqTest.db");
//myDb.createTestMetaData();
//myDb.createQuestionMetadataTable();
//myDb.createMCQOptionTable();
//read_xml_file myxml = new read_xml_file();
//myxml.populateTestMetadataTable();
//myxml.populateQuestionMetadataTable();
//myxml.populateMCQOptionsTable();
//MCQModel objectMCQ = new MCQModel();

   // BasicConfigurator replaced with PropertyConfigurator.
    PropertyConfigurator.configure("log4j.properties");



     logger.info("Entering application.");

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                MCQpresentation mcq_presentation = new MCQpresentation();
		ResultsTable table_view = new ResultsTable();
		MCQbusiness mcq_business = new MCQbusiness(mcq_presentation,table_view);

		mcq_presentation.setExtendedState(mcq_presentation.MAXIMIZED_BOTH); 
		mcq_presentation.setVisible(true);

            }
        });

logger.info("Exiting application.");

    }


     // Define a static logger variable so that it references the
   // Logger instance named "MyApp".
   static Logger logger = Logger.getLogger(MCQbusiness.class);


    //... The Controller needs to interact with the View.
    private MCQpresentation  mcq_presentation;
   // Tracks the current question number
    private ResultsTable table_view;
    private int _questionTracker; 
   // Holds all the answers selected by user
    private String answers[];
   // Holds the current answer
    private String _answer;
   // for testing purposes
    private String question1[] = {"Who is the richest person in the world","Thato Selebogo","Bill Gates","Nelson Mandela","Manny Pacqiou"};
    private String question2[] = {"Who is the lecture of Software Development III","Thato Selebogo","Aveer Ramnath","Ken Nixon","Manny Pacqiou"};
    private String question3[] = {"PHP stands for:","People Hire People","Pick han Pay", "PHP hyper processor", "PHP"};
   // Testing purposes
   private String dbAnswers[] = {"A","B","A",null,"C","D","A","C","B",null,null,null,null,null,null,null,null,null,null,"A"};
   private String userAnswers[] = {"A","D","A",null,"C","D","A","C","B",null,null,null,null,null,null,null,null,null,null,"C"};
    /** Constructor */
    MCQbusiness(MCQpresentation presentation, ResultsTable tableview) {
        mcq_presentation  = presentation;
	table_view = tableview;
	//Start at question 1
	_questionTracker = 1;
	logger.info(Integer.toString(_questionTracker));
	
	answers = new String[20];
        liveUserAnswers = new ArrayList();
        //... Add listeners to the view.
	
        mcq_presentation.addTestBeginListener(new TestBeginListener());
        mcq_presentation.addTestFinishListener(new TestFinishListener());
	mcq_presentation.addNextQListener(new NextQListener());
	mcq_presentation.addPreviousQListener(new PreviousQListener());
	mcq_presentation.addQSelectListener(new QSelectListener());

	
        dbobject_test_metadata =  new dbtables_test_metadata("sqlite","mcqTest.db");
        dbobject_question_metadata =  new dbtables_question_metadata("sqlite","mcqTest.db");
        dbobject_mcq_options =  new dbtables_mcq_options("sqlite","mcqTest.db");
    }


    // return results for the table view
    public Object[][] resultsProcessor()
    {
		Object test[][] = new Object [5][4];
Hashtable questionList= new Hashtable();
ArrayList tempAllQuestionsArray = new ArrayList();
questionList =dbobject_question_metadata.getAllQuestionsFromTable();
Enumeration e = questionList.elements();

Hashtable rightAnswersList= new Hashtable();
rightAnswersList=dbobject_mcq_options.getAllRightAnswers("1");

	for(int i=0; i<5; i++)
        {
	
tempAllQuestionsArray = (ArrayList)  e.nextElement();
			test[i][0] = tempAllQuestionsArray.get(1);
	}
	
	for(int i=0; i<liveUserAnswers.size(); i++)
        {
		
//			
test[i][1] = liveUserAnswers.get(i);; 
	}

	for(int i=0; i<5; i++)
        {
		
			test[i][2] = rightAnswersList.get(i+1);
	}

	for(int i=0; i<liveUserAnswers.size(); i++)
        {
String rightOption = (String) rightAnswersList.get(i+1);
if (liveUserAnswers.get(i) == null)
{
String currentUserOption = "ZZ";
			test[i][3] = "Wrong";
logger.debug("Answer is wrong: (user answer ='null') - (right answer ="+rightOption+")");
}
else
{
String currentUserOption = (String) liveUserAnswers.get(i);
		
if(currentUserOption.equals(rightOption))
		{
			test[i][3] = "Correct";
logger.debug("Answer is correct: (user answer ='"+currentUserOption+") - (right answer ="+rightOption+")");
		}
		else
		{
			test[i][3] = "Wrong";
logger.debug("Answer is wrong: (user answer ='"+currentUserOption+") - (right answer ="+rightOption+")");
		}

}

			
		
	}
	return test;
    }
    

    
    ////////////////////////////////////////// inner class TestBeginListener

    class TestBeginListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
	
	mcq_presentation.initPage2Components();
	logger.debug("Did it again!");
	//System.out.println("my"+_questionTracker);
	mcq_presentation.beginTestButton.setVisible(false);
	//int a = 1;
	//mcq_presentation.setMaxPageNumbers(a);
	mcq_presentation.populatePresentation(_questionTracker);
        }
    }//end inner class TestBeginListener
    
   ////////////////////////////////////////// inner class QSelectListener

    class QSelectListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
	
        
	_answer = e.getActionCommand();

        }
    }//end inner class QSelectListener

   ////////////////////////////////////////// inner class PreviousQListener

    class PreviousQListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
if (_questionTracker >1)
{

logger.debug("Deleting '"+liveUserAnswers.get(_questionTracker-2)+"' as the answer for question "+(_questionTracker-1));
mcq_presentation.questionNumber = mcq_presentation.questionNumber - 1;
	_questionTracker= _questionTracker - 1;
	if(_questionTracker <= 5)
	{
	mcq_presentation.nextButton.setVisible(true);
	}


	 liveUserAnswers.remove(_questionTracker-1);
	iterate();

	mcq_presentation.populatePresentation(_questionTracker);
}	

	
        }
    }//end inner class PreviousQListener

   ////////////////////////////////////////// inner class NextQListener

    class NextQListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
	_questionTracker = _questionTracker + 1;
	if(_questionTracker > 5)
	{
	mcq_presentation.nextButton.setVisible(false);
	}
	mcq_presentation.questionNumber = mcq_presentation.questionNumber + 1;
	mcq_presentation.populatePresentation(_questionTracker);
liveUserAnswers.add(_answer);
iterate();
	answers[_questionTracker] = _answer;

logger.debug("Inserting '"+liveUserAnswers.get(_questionTracker-2)+"' as the answer for question "+(_questionTracker-1));
	
        }
    }//end inner class NextQListener

   ////////////////////////////////////////// inner class TestFinishListener

    class TestFinishListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
	

	mcq_presentation.setVisible(false);
	table_view.setExtendedState(table_view.MAXIMIZED_BOTH); 
	Object[][] results = resultsProcessor();
	table_view.initComponents(results);
	table_view.setVisible(true);

        }
    }//end inner class TestFinishListener



}

